<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Helpers\Helpers;
use App\Model\WineChateau;
use App\Model\WineProduct;
use App\Model\WineProductQrcode;
use App\Model\WineQrcodeRecord;
use Illuminate\Support\Facades\DB;

class WineProductQrcodeRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\Model\WineProductQrcode";

    protected $appendCreatorAndUpdater = true;

    protected $appendUserId = true;

    protected function commonRules()
    {
        return [
            'chateau_id' => 'required',
            'product_id' => 'required',
            'vintage' => 'required',
            'amount' => 'required',
        ];
    }

    protected function commonMessages()
    {
        return [
            'chateau_id.required'   => '未选择酒庄',
            'product_id.required'   => '未选择产品',
            'vintage.required'      => '未选择年份',
            'amount.required'       => '未填发放数量',
        ];
    }

    protected function commonValidate()
    {
        if( !$this->requestValidate($this->commonRules(),$this->commonMessages())) {
            return false;
        }

        if ($this->request->input('amount',0) > 500000){
            $this->error = '一次最大数量500000';
            return false;
        }

        $chateau = WineChateau::find($this->request->input('chateau_id',0));
        $product = WineProduct::find($this->request->input('product_id',0));

        //检查酒庄
        if (!$chateau) {
            $this->error = '该酒庄不存在';
            return false;
        }

        //检查产品
        if (!$product) {
            $this->error = '该产品不存在';
            return false;
        }

        if(!$chateau->produce) {
            $this->error = '酒庄缺少生产商信息，请补充';
            return false;
        }

        if(!$product->country) {
            $this->error = '产品缺少国家信息，请补充';
            return false;
        }

        if(!$product->subdivision) {
            $this->error = '产品缺少地区信息，请补充';
            return false;
        }
        if(!$product->region) {
            $this->error = '产品缺少产区信息，请补充';
            return false;
        }
        if(!$chateau->chateauCode) {
            $this->error = '酒庄缺少酒庄编码信息，请补充';
            return false;
        }

        //检查该酒庄下有无此产品
        $bool = DB::table('wine_product')->where('chateau_id','=',$this->request->input('chateau_id'))
            ->where('id','=',$this->request->input('product_id'))->count() > 0 ? true:false;

        if (!$bool) {
            $this->error = '该酒庄下无此产品，请重新选择';
            return false;
        }

        //挂载数据填充的信息
        $d = [];
        $d['productCode']     = $product->productCode;
        $d['chateauCode']     = $chateau->chateauCode;
        $d['produceCode']     = $chateau->produce->produceCode;
        $d['produce_id']      = $chateau->produce_id;
        $d['countryCode']     = $product->country->countryCode;
        $d['subdivisionCode'] = $product->subdivision->subdivisionCode;
        $d['regionCode']      = $product->region->regionCode;
        $d['region_id']      = $product->region->regionCode;
        $d['subdivision_id']      = $product->subdivision->id;
        $d['country_id']      = $product->country->id;

        $this->propsData['fill'] = $d;

        return true;
    }

    protected function appendStoreFillData()
    {
        $fill = [];
        if($this->propsData['fill']) {
            $fill = $this->propsData['fill'];
        }
        return array_merge($fill,['state'=>1,'remainAmount']);
    }

    //新建
    public function store($request)
    {
        if(!$this->checkAuth('store')) {
            return $this->error;
        }

        if(!$this->storeValidate()) {
            return $this->failed($this->error);
        }

        $fillData = $this->getStoreFillData();

        $model = $this->model()->fill($fillData);

        if($model->beforeSave($this->request->all()) && $model->save() && $model->afterSave()){

            if (!$this->afterStore($model)){
                DB::table('wine_qrcode_record')->where('qrcode_id','=',$model->id)->delete();
                WineProductQrcode::destroy($model->id);
                return $this->failed('二维码生成失败');
            }

            $this->commonSave($model);

            $respond = $this->getStoreRespondData($model);

            $this->saveStoreLog($request,$model);

            return $this->success($respond);
        }

        return $this->failed('创建失败');
    }


    protected function afterStore($model)
    {
        $model->updateRemainAmount();

        $fill = [];
        $fill['state'] = 0; //状态:0预览|1使用中|2使用完|3终止使用
        $fill['qrcode_id'] = $model->id;
        $fill['product_id'] = $model->product_id;
        $fill['countryCode'] = $model->countryCode;             //国家码
        $fill['subdivisionCode'] = $model->subdivisionCode;     //地区码
        $fill['regionCode'] = $model->regionCode;               //产区码
        $fill['chateauCode'] = $model->chateauCode;             //酒庄码
        $fill['productCode'] = $model->productCode;             //产品码
        $fill['produceCode'] = $model->produceCode;             //生产商码
        $fill['vintage'] = $model->vintage;                     //年份码
        $fill['created_at'] = date('Y-m-d H:i:s');

        //产品识别码：国家码+地区码+产区码+酒庄码+产品码+年份码
        $code1 = $model->countryCode.$model->subdivisionCode.$model->regionCode.$model->chateauCode.$model->productCode.$model->vintage;

        $lastSortno = DB::table('wine_qrcode_record')->where('chateauCode','=',$fill['chateauCode'])->orderBy('sortno','desc')
            ->first();

        $sort = 0;

        if ($lastSortno){
            $sort = substr($lastSortno->sortno,strlen($fill['chateauCode']));
        }

        $items = [];
        $t1 = time();

        $bool = true;

        if($model->amount<1000){
            for ($i=1;$i<=$model->amount;$i++){
                $item = [];
                $item['sortno'] = $fill['chateauCode'].sprintf('%09s', $sort+$i);
                $item['uuid'] =  md5($item['sortno'].rand(0,1000).uniqid().str_random(16));
                $item['code'] = $code1.$item['uuid'];

                $items[] = array_merge($fill,$item);
            }
            
            $bo = DB::table('wine_qrcode_record')->insert($items);
            if (!$bo) $bool = false;

        }else {
            for ($i=1;$i<=$model->amount;$i++){
                $item = [];
                $item['sortno'] = $fill['chateauCode'].sprintf('%09s', $sort+$i);
                $item['uuid'] =  md5($item['sortno'].rand(0,1000).uniqid().str_random(16));
                $item['code'] = $code1.$item['uuid'];

                $items[] = array_merge($fill,$item);
                if ($i%1000==0) {
                    $bo = DB::table('wine_qrcode_record')->insert($items);
                    if (!$bo) {
                        $bool = false;
                        break;
                    }
                    $items = [];
                }
            }

            if(count($items) > 0 && count($items) <=1000){
                $bo = DB::table('wine_qrcode_record')->insert($items);
                if (!$bo) $bool = false;
            }

        }
        
        $time = time()-$t1;

        Helpers::log('success:'.$bool.' creator:'.$this->loginUser->id .' '.$this->loginUser->account.' createAmount:'.$model->amount.' time:'.$time,'qrcode_create');

        return $bool;
    }
}